import { revertOssUrl } from '@/utils';
import { PlusOutlined } from '@ant-design/icons';
import { ProForm, ProFormItemProps } from '@ant-design/pro-components';
import { useControllableValue, useUpdateEffect } from 'ahooks';
import { Modal, Upload, UploadFile, message } from 'antd';
import { UploadProps } from 'antd/lib/upload';
import { useState } from 'react';
import URI from 'urijs';
import styles from './index.less';

interface IUploadProps {
  max?: number;
}
const ZLUpload: React.FC<IUploadProps> = ({ max = 1, ...props }) => {
  const [value, onChange] = useControllableValue<string[]>(props);
  const [fileList, setFileList] = useState<UploadProps['fileList']>(
    value?.map((item) => {
      console.log(item);
      return {
        uid: item,
        name: URI(item).filename(),
        url: revertOssUrl(item),
      };
    }),
  );

  useUpdateEffect(() => {
    onChange(
      fileList
        ?.filter((item) => item.url || item.response?.data)
        .map((item) => item.url || item.response?.data) || [],
    );
  }, [fileList]);
  const [preview, setPreview] = useState<UploadFile>();
  const local = JSON.parse(localStorage.getItem('auth') || 'null');
  return (
    <>
      <Upload
        headers={{ Authorization: local.token }}
        accept={props?.accept}
        disabled={props?.disabled}
        maxCount={max}
        listType="picture-card"
        fileList={fileList}
        onPreview={setPreview}
        onChange={(e) => {
          setFileList(e.fileList);
        }}
        beforeUpload={(file) => {
          const isJpgOrPng = file.type.indexOf('image') > -1;
          if (!isJpgOrPng) {
            message.error('请上传图片格式');
          }
          const isLt2M = file.size / 1024 / 1024 > 20;
          if (isLt2M) {
            message.error('文件大小不能超过20M');
          }
          return isJpgOrPng && !isLt2M;
        }}
        action={'/v1/business/file/uploadFile'}
      >
        {(fileList?.length || 0) < max && (
          <div className={styles.button}>
            <PlusOutlined className={styles.icon} />
            <div style={{ marginTop: 8 }}>上传图片</div>
          </div>
        )}
      </Upload>
      <Modal
        title={preview?.name}
        open={!!preview}
        onCancel={() => {
          setPreview(undefined);
        }}
      >
        <img src={preview?.url} style={{ width: '100%' }} />
      </Modal>
    </>
  );
};

export const ProFormUpload: React.FC<ProFormItemProps & IUploadProps> = ({
  max,
  ...props
}) => {
  return (
    <ProForm.Item {...props}>
      <ZLUpload max={max} {...props} />
    </ProForm.Item>
  );
};
